package com.mzj.saas.rent;

import cn.hutool.core.util.ObjectUtil;
import com.mzj.saas.manager.AsyncManager;
import com.mzj.saas.mservice.sys.entity.WechatAccount;
import com.mzj.saas.sdk.pay.callback.WxRefundCallback;
import com.mzj.saas.thread.task.WxCallBackOrderTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * @Author panda
 * @Date 2023/5/4
 **/
@Slf4j
@Controller
@RequestMapping("/rent/wxRefund")
public class WxRefundCallBackController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @RequestMapping("/apartment/callBack")
    @ResponseBody
    public void callBack(HttpServletRequest request, HttpServletResponse response) throws Exception {
        WxRefundCallback wxRefundCallback = new WxRefundCallback(null, request, response);
        Map<String, String> result = wxRefundCallback.verifyResult();
        log.info("订单退款的回调参数：{}", result);
        String returnCode = result.get("return_code");
        String sql = "select * from wechat_account where mch_id = ?";
        List<WechatAccount> account = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(WechatAccount.class), result.get("mch_id"));
        if (ObjectUtil.isEmpty(account)) {
            log.error("订单退款查询不到商户账号配置");
            return;
        }
        result.put("mch_key", account.get(0).getMchApiKey());
        Map<String, String> reqInfo = wxRefundCallback.getReqInfo(result);

        if (!"SUCCESS".equals(returnCode)) log.error("退款业务异常：result：{}、reqInfo：{}",result,reqInfo);
        try {
            //异步处理回调业务
            AsyncManager.me().execute(WxCallBackOrderTask.callBackOrderRefund(reqInfo));
        } catch (Exception e) {
            log.error("小程序退款--公寓订单回调发生了错误：{}", e.getLocalizedMessage());
            wxRefundCallback.resultFail();
        }
        wxRefundCallback.resultSuccess();
    }
}
